<script>
import { createProps, isVnodeFormComponent } from '@/utils/CommonUtils'
import { Divider, Dropdown, Icon, Menu } from 'ant-design-vue'
import { isEmpty } from '@/utils/CommonUtils'

export default {
  name: 'HActionGroup',
  inject: ['getTableInfo'],
  props: {
    title: createProps(String, '操作'),
    align: createProps(String, 'center'),
    width: createProps(Number, 200),
    actionCount: createProps(Number, 3)
  },
  render (h) {
    return h('div', { class: 'h-table-action-group', style: this.groupStyle }, this.renderBody(h))
  },
  methods: {
    renderBody () {
      let slots = (this.$slots.default || []).filter(s => isVnodeFormComponent(s, 'HAction'))
      return this.insertDivider(this.resolveSlots(slots))
    },
    resolveSlots (slots) {
      let res = [], actionGroupSlots = []
      for (let i = 0; i < slots.length; i++) {
        if (i < this.actionCount - 1 || slots.length === this.actionCount) {
          res.push(slots[i])
        } else {
          actionGroupSlots.push(slots[i])
        }
      }
      if (!isEmpty(actionGroupSlots)) {
        res.push(this.createMoreInfoGroup(actionGroupSlots))
      }
      return res
    },
    createMoreInfoGroup (actionGroupSlots) {
      let h = this.$createElement
      return h(Dropdown, [
        this.createMoreInfoButton(h),
        this.createMenus(h, actionGroupSlots)
      ])
    },
    createMenus (h, actionGroupSlots) {
      return h(Menu, { slot: 'overlay' }, this.createcreateMenuItems(h, actionGroupSlots))
    },
    createcreateMenuItems (h, actionGroupSlots) {
      return actionGroupSlots.map(s => {
        return h(Menu.Item, { class: 'h-action-more-info-item' }, [s])
      })
    },
    createMoreInfoButton (h) {
      return h('a', {
        class: 'ant-dropdown-link', on: {
          click: e => e.preventDefault() || e.stopPropagation()
        }
      }, ['更多', h(Icon, { props: { type: 'down' } })])
    },
    createDivider () {
      let h = this.$createElement
      return h(Divider, { props: { type: 'vertical' } })
    },
    insertDivider (slots) {
      let list = []
      for (let i = 0; i < slots.length; i++) {
        if (i != 0) list.push(this.createDivider())
        list.push(slots[i])
      }
      return list
    },
  },
  computed: {
    groupStyle () {
      return {
        textAlign: this.align
      }
    },
    actionColumn () {
      return this.getTableInfo && this.getTableInfo().actionColumn
    }
  },
  watch: {
    actionColumn: {
      handler () {
        if (!this.actionColumn) return
        this.actionColumn.title = this.title
        this.actionColumn.align = this.align
        this.actionColumn.width = this.width
      },
      immediate: true
    }
  }
}
</script>
<style>
.h-table-action-group a {
  color: rgb(64, 169, 255);
}

.h-table-action-group {
  text-align: center;
}

.h-action-more-info-item a:hover {
  color: rgb(64, 169, 255);;
}
</style>